package com.example.controller;

import com.example.vo.LoginParamVO;
import com.example.vo.UserRegisterInfoVO;
import com.example.result.ReturnCode;
import com.example.result.ReturnResult;
import com.example.service.IUserService;
import com.example.utils.JwtUtils;

import com.huawei.innovation.rdm.lwxminibom.dto.entity.UserViewDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/user")
@RestController
@CrossOrigin
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("/login")
    public ReturnResult login(@RequestBody LoginParamVO loginParamVO){
        String name= loginParamVO.getName();
        List<UserViewDTO> userViewDTOS=userService.find(name);
        if(userViewDTOS==null|| userViewDTOS.isEmpty()){
            return new ReturnResult(ReturnCode.USER_NOT_EXIST,"用户不存在");
        }

        UserViewDTO userViewDTO=userViewDTOS.get(0);
        if(!loginParamVO.getPassword().equals(userViewDTO.getPassword())){
            return new ReturnResult(ReturnCode.USER_OR_PASSWORD_NOT_MATCH,"用户名或密码错误");
        }

        Map<String,Object> map=new HashMap<>();
        map.put("user",userViewDTO);
        String token= JwtUtils.generateJwt(map);

        return new ReturnResult(ReturnCode.LOGIN_SUCCESS,"登录成功",token);
    }

    @PostMapping("/register")
    public ReturnResult Register(@RequestBody UserRegisterInfoVO userRegisterInfoVO){
        String name= userRegisterInfoVO.getName();
        List<UserViewDTO> userViewDTOS=userService.find(name);
        if(userViewDTOS!=null){
            return new ReturnResult(ReturnCode.USER_NAME_ALREADY_EXISTED,"用户名已存在");
        }

        // TODO 校验用户名、密码、手机号、邮箱是否符合要求(前端校验OR后端校验）
        if(!userService.validateName(userRegisterInfoVO.getName())){
            return new ReturnResult(ReturnCode.USER_NAME_INVALID,"用户名不符合规范");
        }

        //去除密码校验，在前端校验

        if(!userService.validateEmail(userRegisterInfoVO.getEmail())){
            return new ReturnResult(ReturnCode.EMAIL_INVALID,"邮箱不符合规范");
        }

        if(!userService.validateTelephone(userRegisterInfoVO.getTelephone())){
            return new ReturnResult(ReturnCode.TELEPHONE_INVALID,"手机号不符合规范");
        }

        boolean res=userService.save(userRegisterInfoVO);

        if(res){
            return new ReturnResult(ReturnCode.USER_REGISTER_SUCCESS,"注册成功");
        }else{
            return new ReturnResult(ReturnCode.USER_REGISTER_FAIL,"注册失败");
        }
    }
}


